/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="batchExecute">
    <el-dialog
      :title="$t(`openatc.dutyroute.batchExecutePreview`)"
      :visible.sync="dialogFormVisible"
      width="45%"
      :close-on-click-modal="false"
      @close='closeFormDialog'>
    <div class="content">
      <el-table
        :data="list"
        style="width: 100%"
        :label="$t('openatc.devicemanager.devicename')"
        :height="500"
        :default-sort = "{prop: 'm_unFaultOccurTime', order: 'descending'}"
       >
        <el-table-column
          type="index"
          label="#"
          align="center">
        </el-table-column>
        <el-table-column
          prop="name"
          :label="$t('openatc.devicemanager.devicename')"
          align="center"
          width="240">
        </el-table-column>
        <el-table-column
          prop="roles"
          :label="$t('openatc.devicemanager.state')"
          align="center">
            <template  slot-scope="scope">
              <div>
                <el-tooltip placement="top-start" effect="light" popper-class="atooltip">
                  <div slot="content">{{$t('openatc.devicemanager.lastupdatetime')}}:{{scope.row.lastTime}}</div>
                  <el-tag style="cursor:pointer;"  size="medium" effect="plain" :type="getTag(scope.row).type">{{ getTag(scope.row).label }}</el-tag>
                </el-tooltip>
              </div>
            </template>
        </el-table-column>
        <el-table-column
          prop="control"
          :label="$t('openatc.devicemanager.controlMode')"
          align="center">
          <template  slot-scope="scope">
            <div v-if="scope.row.state === 'DOWN'">
              --
            </div>
            <div v-if="getMode(scope.row).type && scope.row.state ==='UP'">
              <el-tag  style="cursor:pointer;"  size="medium" effect="plain" :type="getMode(scope.row).type">{{ getMode(scope.row).label }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="control"
          :label="$t('openatc.dutyroute.executionway')"
          align="center">
          <template  slot-scope="scope">
            {{ getContent(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="enumerate"
          :label="$t('openatc.bottleneckcontrol.executeresults')"
          align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.executeresults === 1">
              <span class="success">
                <i class="el-icon-check success"></i>
              </span>
              {{$t('openatc.greenwaveoptimize.updated')}}
            </div>
            <div v-else-if="scope.row.executeresults === 2">
              <span class="danger">
                <i class="el-icon-close"></i>
              </span>
              {{$t('openatc.greenwaveoptimize.failed')}}
              <span class="primary">
                <i class="el-icon-search" @click="onErrorDetailClick(scope.row)"></i>
              </span>
            </div>
            <div v-else-if="scope.row.executeresults === 3">
              -- {{$t('openatc.greenwaveoptimize.ignored')}}
            </div>
            <div v-else>
              --
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <div class="checkbox">
        <el-checkbox v-model="checked" v-show="false">{{$t('openatc.greenwaveoptimize.continueOnfailure')}}</el-checkbox>
      </div>
      <div class="time">
        <div class="time-content" v-show="bizType === 'executePlan1'">
          <div style="width:37%;">
            {{$t('openatc.greenwaveoptimize.executeTime')}}
          </div>
          <div style="width:14%;">
            <el-select style="float:right;width:80px" v-model="hour" size="small" @change="handleSort">
              <el-option
                v-for="item in HoursOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div style="width:4%;display:flex;justify-content:center;">
            <span>:</span>
          </div>
          <div style="width:14%;">
            <el-select style="float:left;width:80px" v-model="minute" size="small"  @change="handleSort">
              <el-option
                v-for="item in MinuteOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="button" v-if="bizType === 'executePlan'">
        <el-button type="primary" size="small" @click="onExecuteNowClick" plain>{{$t('openatc.dutyroute.executenow')}}</el-button>
        <el-button type="primary" size="medium" @click="onRecoverNowClick" plain>{{$t('openatc.greenwaveoptimize.backSelfControl')}}</el-button>
      </div>
      <div class="button" v-else>
        <el-button type="primary" size="medium" @click="onDownSendClick" plain>{{$t('openatc.greenwaveoptimize.saveParams')}}</el-button>
      </div>
    </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMessageByCode } from '../../../utils/responseMessage'
import { GetDeviceByIds } from '../../../api/device'
import { putControl } from '../../../api/control'
import { ExecuteViproute } from '../../../api/service'
import ServiceUtil from '../serviceUtil.js'
export default {
  name: 'PlanExecute',
  props: {
    childTitle: {
      type: String
    }
  },
  data () {
    return {
      serviceUtil: {},
      checked: true,
      bizType: 'executePlan',
      routeId: 0,
      dialogFormVisible: false,
      deviceInfo: {},
      hour: 0,
      minute: 5,
      HoursOption: [
        {
          value: 0,
          label: '00'
        },
        {
          value: 1,
          label: '01'
        },
        {
          value: 2,
          label: '02'
        },
        {
          value: 3,
          label: '03'
        },
        {
          value: 4,
          label: '04'
        },
        {
          value: 5,
          label: '05'
        },
        {
          value: 6,
          label: '06'
        },
        {
          value: 7,
          label: '07'
        },
        {
          value: 8,
          label: '08'
        },
        {
          value: 9,
          label: '09'
        },
        {
          value: 10,
          label: '10'
        },
        {
          value: 11,
          label: '11'
        },
        {
          value: 12,
          label: '12'
        },
        {
          value: 13,
          label: '13'
        },
        {
          value: 14,
          label: '14'
        },
        {
          value: 15,
          label: '15'
        },
        {
          value: 16,
          label: '16'
        },
        {
          value: 17,
          label: '17'
        },
        {
          value: 18,
          label: '18'
        },
        {
          value: 19,
          label: '19'
        },
        {
          value: 20,
          label: '20'
        },
        {
          value: 21,
          label: '21'
        },
        {
          value: 22,
          label: '22'
        },
        {
          value: 23,
          label: '23'
        }
      ],
      MinuteOption: [
        {
          value: 0,
          label: '00'
        },
        {
          value: 1,
          label: '01'
        },
        {
          value: 2,
          label: '02'
        },
        {
          value: 3,
          label: '03'
        },
        {
          value: 4,
          label: '04'
        },
        {
          value: 5,
          label: '05'
        },
        {
          value: 6,
          label: '06'
        },
        {
          value: 7,
          label: '07'
        },
        {
          value: 8,
          label: '08'
        },
        {
          value: 9,
          label: '09'
        },
        {
          value: 10,
          label: '10'
        },
        {
          value: 11,
          label: '11'
        },
        {
          value: 12,
          label: '12'
        },
        {
          value: 13,
          label: '13'
        },
        {
          value: 14,
          label: '14'
        },
        {
          value: 15,
          label: '15'
        },
        {
          value: 16,
          label: '16'
        },
        {
          value: 17,
          label: '17'
        },
        {
          value: 18,
          label: '18'
        },
        {
          value: 19,
          label: '19'
        },
        {
          value: 20,
          label: '20'
        },
        {
          value: 21,
          label: '21'
        },
        {
          value: 22,
          label: '22'
        },
        {
          value: 23,
          label: '23'
        },
        {
          value: 24,
          label: '24'
        },
        {
          value: 25,
          label: '25'
        },
        {
          value: 26,
          label: '26'
        },
        {
          value: 27,
          label: '27'
        },
        {
          value: 28,
          label: '28'
        },
        {
          value: 29,
          label: '29'
        },
        {
          value: 30,
          label: '30'
        },
        {
          value: 31,
          label: '31'
        },
        {
          value: 32,
          label: '32'
        },
        {
          value: 33,
          label: '33'
        },
        {
          value: 34,
          label: '34'
        },
        {
          value: 35,
          label: '35'
        },
        {
          value: 36,
          label: '36'
        },
        {
          value: 37,
          label: '37'
        },
        {
          value: 38,
          label: '38'
        },
        {
          value: 39,
          label: '39'
        },
        {
          value: 40,
          label: '40'
        },
        {
          value: 41,
          label: '41'
        },
        {
          value: 42,
          label: '42'
        },
        {
          value: 43,
          label: '43'
        },
        {
          value: 44,
          label: '44'
        },
        {
          value: 45,
          label: '45'
        },
        {
          value: 46,
          label: '46'
        },
        {
          value: 47,
          label: '47'
        },
        {
          value: 48,
          label: '48'
        },
        {
          value: 49,
          label: '49'
        },
        {
          value: 50,
          label: '50'
        },
        {
          value: 51,
          label: '51'
        },
        {
          value: 52,
          label: '52'
        },
        {
          value: 53,
          label: '53'
        },
        {
          value: 54,
          label: '54'
        },
        {
          value: 55,
          label: '55'
        },
        {
          value: 56,
          label: '56'
        },
        {
          value: 57,
          label: '57'
        },
        {
          value: 58,
          label: '58'
        },
        {
          value: 59,
          label: '59'
        }
      ],
      list: []
    }
  },
  created () {
    this.serviceUtil = new ServiceUtil()
  },
  methods: {
    onViewClick (list) {
      this.dialogFormVisible = !this.dialogFormVisible
      this.list = list
    },
    onErrorDetailClick (row) {
      let msg = row.msg
      let title = this.$t('openatc.bottleneckcontrol.controlfailed')
      this.$alert(msg, title, {
        confirmButtonText: this.$t('openatc.button.OK'),
        callback: action => {}
      })
    },
    async onExecuteClick (id, routeData) {
      this.bizType = 'executePlan'
      this.routeId = id
      let list = await this.getList(routeData)
      this.onViewClick(list)
    },
    onDownSendClick () {
      let reqData = this.routeData
      let duration = this.hour * 60 * 60 + this.minute * 60
      reqData.duration = duration
      reqData.continueOnfailure = this.checked
      this.doSend(reqData)
    },
    doSend (reqData) {
      let planContent = this.$parent.$refs.planContent
      planContent.handleDownload(this.routeId, reqData).then(res => {
        this.handeleResponse(res)
      })
    },
    getContent (row) {
      let res = this.serviceUtil.getContent(row)
      // if (res === '') {
      //   res = row.controlName
      // }
      return res
    },
    async handeleResponse (res) {
      let statusdata = res.data.data.statusdata
      for (let status of statusdata) {
        let agentid = status.data.agentid
        let msg = status.data.errorMsg
        let row = this.list.filter(item => item.agentid === agentid)[0]
        if (msg) {
          row.executeresults = 2
        } else {
          row.executeresults = 1
        }
        row.msg = msg
      }
      let devList = await this.getList(this.routeData)
      this.list.map(item => {
        if (!item.executeresults) {
          item.executeresults = 3
        }
        let dev = devList.filter(record => record.agentid === item.agentid)[0]
        item.state = dev.state
        item.mode = dev.mode
        item.control = dev.control
      })
      if (statusdata) {
        this.$alert(this.$t('openatc.common.operationsuccess'), { type: 'success' })
      }
    },
    async batchExec (param) {
      let statusdataArr = []
      const messages = param.messages
      for (let reqData of messages) {
        let errorMsg = await this.executeViproute(reqData)
        let statusdata = {
          success: false,
          data: {
            agentid: reqData.agentid,
            errorMsg: errorMsg,
            errorCode: ''
          }
        }
        statusdataArr.push(statusdata)
      }
      let res = {
        data: {
          data: {
            statusdata: statusdataArr
          }
        }
      }
      return res
    },
    async executeViproute (reqData) {
      let msg = ''
      return new Promise((resolve, reject) => {
        ExecuteViproute(reqData).then(res => {
          if (!res.data.success) {
            msg = getMessageByCode(res.data.code, this.$i18n.locale)
            if (res.data.data) {
              let errorCode = res.data.data.errorCode
              if (errorCode) {
                msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
              }
            }
          } else {
            if (res.data.data && res.data.data.data) {
              let success = res.data.data.data.success
              if (success !== 0) {
                // 手动面板控制提示
                let errormsg = 'openatccomponents.overview.putTscControlError' + success
                msg = errormsg
                return msg
              }
            }
          }
          resolve(msg)
        })
      })
    },
    async onRecoverNowClick () {
      let reqData = this.getReqData(this.list, 2)
      let res = await this.batchExec(reqData)
      this.handeleResponse(res)
    },
    async onExecuteNowClick () {
      let reqData = this.getReqData(this.list, 1)
      let res = await this.batchExec(reqData)
      this.handeleResponse(res)
    },
    getReqData (list, id) {
      let param = {
        'continueOnfailure': this.checked,
        'messages': []
      }
      let messages = []
      this.list.map(row => {
        if (row.isused && row.state === 'UP') {
          let reqData = this.getRowReqData(row, id)
          messages.push(reqData)
        }
      })
      param.messages = messages
      return param
    },
    getRowReqData (row, id) {
      let message = {}
      if (id === 1) { // 1 临时，2.恢复，3.下载
        message = {
          'agentid': row.agentid,
          'viprouteid': row.viprouteid,
          'operation': 1
        }
      } else if (id === 2) { // 1 临时，2.恢复，3.下载
        message = {
          'agentid': row.agentid,
          'viprouteid': row.viprouteid,
          'operation': 0
        }
      }
      return message
    },
    async onDownloadClick (id, routeData) {
      this.bizType = 'downloadPlan'
      this.routeId = id
      let list = await this.getList(routeData)
      this.onViewClick(list)
    },
    async getList (routeData) {
      this.routeData = routeData
      let deviceIds = this.routeData.devs.map(ele => ele.agentid)
      let devList = await this.getDeviceByIds(deviceIds)
      let list = routeData.devs
      list = list.map(dev => {
        let item = devList.filter(de => de.agentid === dev.agentid)[0]
        dev = {...dev, ...item}
        dev.executeresults = dev.executeresults ? dev.executeresults : 0
        dev.msg = dev.msg ? dev.msg : ''
        dev.isused = true
        return dev
      })
      return list
    },
    async putControls (devList) {
      for (let dev of devList) {
        dev.isExecuted = true
        let controlParam = dev.controlParam
        if (!dev.isused || dev.state === 'DOWN') {
          continue
        }
        let message = await this.putControl(controlParam)
        dev.message = message
      }
    },
    async putControl (reqData) {
      let message = ''
      let data = await putControl(reqData)
      let success = 0
      if (!data.data.success) {
        message = getMessageByCode(data.data.code, this.$i18n.locale)
      } else {
        if (data.data.data && data.data.data.data) {
          success = data.data.data.data.success
          if (success !== 0) {
            let errormsg = 'openatccomponents.overview.putTscControlError' + success
            message = errormsg
          }
        }
      }
      return message
    },
    async getDeviceByIds (deviceIds) {
      // 获取设备表格信息
      let devicesData = []
      let _this = this
      return new Promise((resolve, reject) => {
        GetDeviceByIds(deviceIds).then(res => {
          if (!res.data.success) {
            _this.$message.error(getMessageByCode(res.data.code, _this.$i18n.locale))
            resolve(devicesData)
          }
          devicesData = res.data.data
          resolve(devicesData)
        })
      })
    },
    getMode (row) {
      if (row.control === 0) {
        return {
          label: this.$t('openatccomponents.overview.modelList0'),
          type: 'success'
        }
      } else if (row.control === 1) {
        return {
          label: this.$t('openatccomponents.overview.modelList1'),
          type: 'warning'
        }
      } else if (row.control === 2) {
        return {
          label: this.$t('openatccomponents.overview.modelList2'),
          type: 'warning'
        }
      } else if (row.control === 3) {
        return {
          label: this.$t('openatccomponents.overview.modelList3'),
          type: 'warning'
        }
      } else if (row.control === 4) {
        return {
          label: this.$t('openatccomponents.overview.modelList4'),
          type: 'warning'
        }
      } else if (row.control === 22) {
        return {
          label: this.$t('openatccomponents.overview.modelList22'),
          type: 'warning'
        }
      } else if (row.control === 5) {
        return {
          label: this.$t('openatccomponents.overview.modelList5'),
          type: 'success'
        }
      } else if (row.control === 6) {
        return {
          label: this.$t('openatccomponents.overview.modelList6'),
          type: 'success'
        }
      } else if (row.control === 7) {
        return {
          label: this.$t('openatccomponents.overview.modelList7'),
          type: 'success'
        }
      } else if (row.control === 8) {
        return {
          label: this.$t('openatccomponents.overview.modelList8'),
          type: 'success'
        }
      } else if (row.control === 9) {
        return {
          label: this.$t('openatccomponents.overview.modelList9'),
          type: 'success'
        }
      } else if (row.control === 10) {
        return {
          label: this.$t('openatccomponents.overview.modelList10'),
          type: 'success'
        }
      } else if (row.control === 11) {
        return {
          label: this.$t('openatccomponents.overview.modelList11'),
          type: 'success'
        }
      } else if (row.control === 12) {
        return {
          label: this.$t('openatccomponents.overview.modelList12'),
          type: 'success'
        }
      } else if (row.control === 13) {
        return {
          label: this.$t('openatccomponents.overview.modelList13'),
          type: 'success'
        }
      } else if (row.control === 14) {
        return {
          label: this.$t('openatccomponents.overview.modelList14'),
          type: 'success'
        }
      } else if (row.control === 15) {
        return {
          label: this.$t('openatccomponents.overview.modelList15'),
          type: 'success'
        }
      } else if (row.control === 16) {
        return {
          label: this.$t('openatccomponents.overview.modelList16'),
          type: 'success'
        }
      } else if (row.control === 17) {
        return {
          label: this.$t('openatccomponents.overview.modelList17'),
          type: 'success'
        }
      } else if (row.control === 18) {
        return {
          label: this.$t('openatccomponents.overview.modelList18'),
          type: 'success'
        }
      } else if (row.control === 19) {
        return {
          label: this.$t('openatccomponents.overview.modelList19'),
          type: 'success'
        }
      } else if (row.control === 21) {
        return {
          label: this.$t('openatccomponents.overview.modelList21'),
          type: 'success'
        }
      } else if (row.control === 23) {
        return {
          label: this.$t('openatccomponents.overview.modelList23'),
          type: 'success'
        }
      } else if (row.control === 24) {
        return {
          label: this.$t('openatccomponents.overview.modelList24'),
          type: 'success'
        }
      } else if (row.control === 99) {
        return {
          label: this.$t('openatccomponents.overview.modelList25'),
          type: 'success'
        }
      } else if (row.control === 100) {
        return {
          label: this.$t('openatccomponents.overview.modelList100'),
          type: 'success'
        }
      } else if (!row.control) {
        return {
          label: '',
          type: ''
        }
      }
    },
    getType (row) {
      if (row.mode === 0) {
        return {
          label: this.$t('openatc.patternstatistic.mode0'),
          type: 'success'
        }
      } else if (row.mode === 1) {
        return {
          label: this.$t('openatc.patternstatistic.mode1'),
          type: 'warning'
        }
      } else if (row.mode === 2) {
        return {
          label: this.$t('openatc.patternstatistic.mode2'),
          type: 'warning'
        }
      } else if (row.mode === 3) {
        return {
          label: this.$t('openatc.patternstatistic.mode3'),
          type: 'warning'
        }
      } else if (row.mode === 4) {
        return {
          label: this.$t('openatc.patternstatistic.mode4'),
          type: 'warning'
        }
      } else if (row.mode === 5) {
        return {
          label: this.$t('openatc.patternstatistic.mode5'),
          type: 'warning'
        }
      } else if (row.mode === 6) {
        return {
          label: this.$t('openatc.patternstatistic.mode6'),
          type: 'warning'
        }
      } else if (row.mode === 7) {
        return {
          label: this.$t('openatc.patternstatistic.mode7'),
          type: 'warning'
        }
      } else if (row.mode === 8) {
        return {
          label: this.$t('openatc.patternstatistic.mode8'),
          type: 'warning'
        }
      } else if (!row.mode) {
        return {
          label: '',
          type: ''
        }
      }
    },
    getTag (row) {
      if (row.state === 'DOWN') {
        return {
          label: this.$t('openatc.devicemanager.offline'),
          type: 'info'
        }
      } else {
        if (row.status === 0) {
          // 数据从设备端来，暂时写死，0代表正常状态，其余数字均代表一种类型的故障
          return {
            label: this.$t('openatc.devicemanager.online'),
            type: 'success'
          }
        } else {
          // return {
          //   label: this.$t('openatc.devicemanager.fault'),
          //   type: 'danger'
          // }
        }
      }
    },
    closeFormDialog () {
      this.checked = true
      this.hour = 0
      this.minute = 5
      this.$emit('research')
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss">
.dev-update .el-dialog__body {
  padding: 30px 72px 30px 0;
}
.el-dialog__footer {
  padding: 10px 72px 38px 0;
}
</style>
